// 83. 删除排序链表中的重复元素
// https://leetcode.cn/problems/remove-duplicates-from-sorted-list/description/

/**
 * 
输入：head = [1,1,2]
输出：[1,2]

输入：head = [1,1,2,3,3]
输出：[1,2,3]
 */

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var deleteDuplicates = function (head) {
    if (!head) {
        return head;
    }

    // let newHead = head;
    // 初始化操作
    // 记录前两个元素
    let prev = head;
    let cur = head;

    while (cur.next) {
        cur = cur.next;
        if (cur.val === prev.val) {
            prev.next = cur.next;
        } else {
            prev = cur;
        }
    }
    return head;
};

function listNode(arr) {
    console.log(`[listNode] arr is ${JSON.stringify(arr)}`);
    if (!arr || arr.length < 1) {
        return null;
    }

    let ret = {
        val: null,
        next: null,
    };
    let temp = ret;
    for (let i = 0; i < arr.length; i++) {
        temp.val = arr[i];
        temp.next = null;
        if (i < arr.length - 1) {
            temp.next = {
                val: null,
                next: null,
            };
        }

        temp = temp.next;
    }
    // console.log(`[listNode complete] ret is ${JSON.stringify(ret)}`);
    return ret;
}

function flat(listNode) {
    if (listNode == null) {
        console.log(`flat: node is ${JSON.stringify([])}`);
        return [];
    }

    let arr = [];
    let node = listNode;
    // console.log(`flat: node is ${JSON.stringify(node)}`);
    do {
        arr.push(node.val);
        node = node.next;
    } while (!!node && !!node.next);
    if (!!node) {
        arr.push(node.val);
    }

    console.log(`flat complete: arr is ${JSON.stringify(arr)}`);
    return arr;
}

/**
 * 输入：head = [1,2,3,3,4,4,5]
输出：[1,2,5]
 */
flat(deleteDuplicates(listNode([1, 1, 2])));
flat(deleteDuplicates(listNode([1, 1, 2, 3, 3])));
flat(deleteDuplicates(listNode([1, 2, 3, 3, 4, 4, 5])));
flat(deleteDuplicates(listNode([1, 1, 1, 2, 3])));
flat(deleteDuplicates(listNode([1, 1, 1, 1])));
flat(deleteDuplicates(listNode([1, 1, 2, 2])));
flat(deleteDuplicates(listNode([1, 2, 2])));
flat(deleteDuplicates(listNode([1, 2, 2, 2])));
